#include <pspiofilemgr.h>
#include "config.h"
#include "io_util.h"
#include "memory.h"

void make_32_be(uint32_t *x)
{
	*x = (*x << 8 & 0xFF00FF00) | (*x >> 8 & 0x00FF00FF);
	*x = (*x >> 16) | (*x << 16);
}

void make_16_be(uint16_t *x)
{
	*x = (*x << 8 & 0xFF00) | (*x >> 8 & 0x00FF);
}

uint32_t read_32_be(SceUID file)
{
	uint32_t num;
	sceIoRead(file, &num, 4);
	make_32_be(&num);
	return num;
}

uint16_t read_16_be(SceUID file)
{
	uint16_t num;
	sceIoRead(file, &num, 2);
	make_16_be(&num);
	return num;
}

uint8_t read_8_be(SceUID file)
{
	uint8_t num;
	sceIoRead(file, &num, 1);
	return num;
}

uint32_t seek_32_be(SceUID file)
{
	uint32_t num;
	num = read_32_be(file);
	sceIoLseek(file, -4, PSP_SEEK_CUR);
	return num;
}

uint16_t seek_16_be(SceUID file)
{
	uint16_t num;
	num = read_16_be(file);
	sceIoLseek(file, -2, PSP_SEEK_CUR);
	return num;
}

void read_8_str(SceUID file, char **str)
{
	uint8_t len = read_8_be(file);
	*str = shin_malloc(len + 1);
	sceIoRead(file, *str, len);
	(*str)[len] = 0;
}

void read_16_str(SceUID file, char **str)
{
	uint16_t len = read_16_be(file);
	*str = shin_malloc(len + 1);
	sceIoRead(file, *str, len);
	(*str)[len] = 0;
}

void skip_bytes(SceUID file, uint32_t num)
{
	sceIoLseek(file, num, PSP_SEEK_CUR);
}

void skip_8_str(SceUID file)
{
	uint8_t len = read_8_be(file);
	sceIoLseek(file, len, PSP_SEEK_CUR);
}

void skip_16_str(SceUID file)
{
	uint16_t len = read_16_be(file);
	sceIoLseek(file, len, PSP_SEEK_CUR);
}
